/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package viewControl;

import entity.*;
import java.awt.Desktop;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JSpinner.DateEditor;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.hibernate.HibernateException;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.Query;
import org.hibernate.Session;
import util.FileUtils;
import util.GUIUtils;
import util.PrintUtils;

/**
 *
 * @author Jeppe Andersen
 */
public class ElevPanel extends javax.swing.JPanel {

    private File billedefil;
    private ArrayList allergier;
    private ArrayList medicin;
    private ArrayList filer;
    private ArrayList filerDerSlettes;
    private Session session;
    private boolean needtoupdate;
    private Laerer currentLaerer;

    /**
     * Creates new form ElevPanel
     */
    public ElevPanel(Session session) {
        this.session = session;
        this.currentLaerer = null;
        needtoupdate = false;
        allergier = new ArrayList();
        medicin = new ArrayList();
        filer = new ArrayList();
        filerDerSlettes = new ArrayList();
        initComponents();
    }

    public ElevPanel(Session session, Laerer laerer) {
        this.session = session;
        this.currentLaerer = laerer;
        needtoupdate = false;
        allergier = new ArrayList();
        medicin = new ArrayList();
        filer = new ArrayList();
        initComponents();
    }

    public String getByNavn(String postnr) {
        String result;
        String hql = "from Postnrbynavn where postnr='" + postnr + "'";
        session.beginTransaction();
        Query q = session.createQuery(hql);
        try {
            Postnrbynavn pbn = (Postnrbynavn) q.uniqueResult();
            result = pbn.getBynavn();
        } catch (NullPointerException e) {
            result = "Ugyldigt Postnr.";
        }
        return result;
    }

    public String getElevTlf(String cpr) {
        String result = null;
        String hqltlf = "from Elevtlf where cpr='" + cpr + "'";
        session.beginTransaction();
        Query q = session.createQuery(hqltlf);
        try {
            Elevtlf etlf = (Elevtlf) q.uniqueResult();
            result = etlf.getId().getTlfNr();
        } catch (Exception e) {
        }
        return result;
    }
    
    public void limitPanel(){
        btnSletElev.setVisible(false);
    }

    protected void update() {
        Elev elevIndex = null;
        if (cbElevNavn.getSelectedIndex() > 0) {
            elevIndex = (Elev) cbElevNavn.getSelectedItem();
        } else {
            lIconBilledeElev.setIcon(null);
            elevBilledePanel.validate();
            this.revalidate();
            this.repaint();
        }
        cbElevNavn.setSelectedIndex(0);

        if (currentLaerer == null) {
            // Updater elev combobox med alle elever
            cbElevNavn.removeAllItems();
            cbElevNavn.addItem("Elev");
            String hql = "from Elev";
            try {
                session.beginTransaction();
                Query q = session.createQuery(hql);
                Object[] eList = q.list().toArray();
                Arrays.sort(eList);
                for (int i = 0; i < eList.length; i++) {
                    cbElevNavn.addItem(eList[i]);
                }
                session.getTransaction().commit();
            } catch (HibernateException he) {
                System.out.println(he.getLocalizedMessage());
            }
        } else if (currentLaerer != null) {
            // Updater elev combobox med lærerens elever 
            cbElevNavn.removeAllItems();
            cbElevNavn.addItem("Elev");
            ArrayList holdfags = new ArrayList();
            ArrayList elever = new ArrayList();
            ArrayList finallist = new ArrayList();
            holdfags.addAll(currentLaerer.getHoldfags());
            for (int i = 0; i < holdfags.size(); i++) {
                Holdfag hf = (Holdfag) holdfags.get(i);
                elever.addAll(hf.getHold().getElevs());
                for (int j = 0; j < elever.size(); j++) {
                    Elev e = (Elev) elever.get(i);
                    if (!finallist.contains(e)) {
                        finallist.add(e);                        
                    }
                }
            }
            Object[] eList = finallist.toArray();
                Arrays.sort(eList);
                for (int i = 0; i < eList.length; i++) {
                    cbElevNavn.addItem(eList[i]);
                }
        }

        //Updater hold combobox
        cbElevHold.removeAllItems();
        cbElevHold.addItem("Hold");
        String hql = "from Hold";
        try {
            session.beginTransaction();
            Query q = session.createQuery(hql);
            List resultList = q.list();
            for (int i = 0; i < resultList.size(); i++) {
                cbElevHold.addItem((Hold) resultList.get(i));

            }
            session.getTransaction().commit();
        } catch (HibernateException he) {
            System.out.println(he.getLocalizedMessage());
        }

        //ryd alle felter
        GUIUtils.clearFields(this);
        if (elevIndex != null) {
            cbElevNavn.setSelectedItem(elevIndex);
        } else {
            cbElevNavn.setSelectedIndex(0);
        }
        if (cbElevNavn.getSelectedIndex() > 0) {
            btnGemElev.setText("Gem ændringer");
        } else {
            btnGemElev.setText("Opret ny elev");
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cbElevNavn = new javax.swing.JComboBox();
        txtElevEnavn = new javax.swing.JTextField();
        txtElevFnavn = new javax.swing.JTextField();
        txtElevAdress = new javax.swing.JTextField();
        txtElevPostnr = new javax.swing.JTextField();
        txtElevAllergi = new javax.swing.JTextField();
        txtElevMobilNr = new javax.swing.JTextField();
        cbElevHold = new javax.swing.JComboBox();
        cbElevKlasseTrin = new javax.swing.JComboBox();
        txtElevRekvKommune = new javax.swing.JTextField();
        txtElevRekvSkole = new javax.swing.JTextField();
        txtElevMedicin = new javax.swing.JTextField();
        chbIndskrevet = new javax.swing.JCheckBox();
        spElevIndskrevet = new javax.swing.JSpinner();
        chbUdskrevet = new javax.swing.JCheckBox();
        spElevUdskrevet = new javax.swing.JSpinner();
        jLabel6 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        elevBilledePanel = new javax.swing.JPanel();
        lIconBilledeElev = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtElevBy = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        btnElevTilfojAllergi = new javax.swing.JButton();
        jScrollPane8 = new javax.swing.JScrollPane();
        listElevAllergi = new javax.swing.JList();
        btnElevSletAllergi = new javax.swing.JButton();
        jLabel13 = new javax.swing.JLabel();
        btnElevTilfojMedicin = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        listElevMedicin = new javax.swing.JList();
        btnElevSletMedicin = new javax.swing.JButton();
        btnInsertBillede = new javax.swing.JButton();
        btnGemElev = new javax.swing.JButton();
        btnSletElev = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtaElevNote = new javax.swing.JTextArea();
        jScrollPane6 = new javax.swing.JScrollPane();
        listFiler = new javax.swing.JList();
        jLabel25 = new javax.swing.JLabel();
        btnVedhaeftFil = new javax.swing.JButton();
        btnOpenFil = new javax.swing.JButton();
        btnFjernValgteFil = new javax.swing.JButton();
        btnPrint = new javax.swing.JButton();
        txtElevcpr = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jSeparator3 = new javax.swing.JSeparator();
        jSeparator4 = new javax.swing.JSeparator();
        jButton1 = new javax.swing.JButton();
        btnFortryd = new javax.swing.JButton();

        setLayout(null);

        cbElevNavn.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Elev" }));
        cbElevNavn.setToolTipText("");
        cbElevNavn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbElevNavnActionPerformed(evt);
            }
        });
        add(cbElevNavn);
        cbElevNavn.setBounds(10, 11, 165, 20);
        add(txtElevEnavn);
        txtElevEnavn.setBounds(390, 60, 170, 20);
        add(txtElevFnavn);
        txtElevFnavn.setBounds(200, 60, 170, 20);
        add(txtElevAdress);
        txtElevAdress.setBounds(10, 110, 170, 20);

        txtElevPostnr.setNextFocusableComponent(txtElevMobilNr);
        txtElevPostnr.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtElevPostnrKeyReleased(evt);
            }
        });
        add(txtElevPostnr);
        txtElevPostnr.setBounds(200, 110, 170, 20);
        add(txtElevAllergi);
        txtElevAllergi.setBounds(200, 220, 170, 20);
        add(txtElevMobilNr);
        txtElevMobilNr.setBounds(10, 160, 170, 20);

        cbElevHold.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Hold" }));
        cbElevHold.setNextFocusableComponent(chbIndskrevet);
        add(cbElevHold);
        cbElevHold.setBounds(390, 260, 170, 20);

        cbElevKlasseTrin.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Klassetrin", "1 Klasse", "2 Klasse", "3 Klasse", "4 Klasse", "5 Klasse", "6 Klasse", "7 Klasse", "8 Klasse", "9 Klasse", "10 Klasse" }));
        cbElevKlasseTrin.setToolTipText("");
        cbElevKlasseTrin.setNextFocusableComponent(cbElevHold);
        add(cbElevKlasseTrin);
        cbElevKlasseTrin.setBounds(390, 220, 170, 20);
        add(txtElevRekvKommune);
        txtElevRekvKommune.setBounds(200, 160, 170, 20);
        add(txtElevRekvSkole);
        txtElevRekvSkole.setBounds(390, 160, 170, 20);
        add(txtElevMedicin);
        txtElevMedicin.setBounds(10, 220, 170, 20);

        chbIndskrevet.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        chbIndskrevet.setText("Indskrevet");
        add(chbIndskrevet);
        chbIndskrevet.setBounds(580, 280, 100, 23);

        spElevIndskrevet.setModel(new javax.swing.SpinnerDateModel());
        spElevIndskrevet.setEditor(new DateEditor(spElevIndskrevet, "dd-MM-yyyy"));
        add(spElevIndskrevet);
        spElevIndskrevet.setBounds(580, 310, 110, 20);

        chbUdskrevet.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        chbUdskrevet.setText("Udskrevet");
        add(chbUdskrevet);
        chbUdskrevet.setBounds(580, 360, 100, 23);

        spElevUdskrevet.setModel(new javax.swing.SpinnerDateModel());
        spElevUdskrevet.setEditor(new DateEditor(spElevUdskrevet, "dd-MM-yyyy"));
        add(spElevUdskrevet);
        spElevUdskrevet.setBounds(580, 390, 110, 20);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setText("CPR nr.");
        add(jLabel6);
        jLabel6.setBounds(10, 40, 50, 14);

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel10.setText("Rekvirerende Kommune");
        add(jLabel10);
        jLabel10.setBounds(200, 140, 150, 14);

        lIconBilledeElev.setText("Elev Billede");

        javax.swing.GroupLayout elevBilledePanelLayout = new javax.swing.GroupLayout(elevBilledePanel);
        elevBilledePanel.setLayout(elevBilledePanelLayout);
        elevBilledePanelLayout.setHorizontalGroup(
            elevBilledePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(elevBilledePanelLayout.createSequentialGroup()
                .addComponent(lIconBilledeElev)
                .addGap(0, 137, Short.MAX_VALUE))
        );
        elevBilledePanelLayout.setVerticalGroup(
            elevBilledePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(elevBilledePanelLayout.createSequentialGroup()
                .addComponent(lIconBilledeElev)
                .addGap(0, 206, Short.MAX_VALUE))
        );

        add(elevBilledePanel);
        elevBilledePanel.setBounds(580, 10, 190, 220);

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel11.setText("Rekvirerende Skole");
        add(jLabel11);
        jLabel11.setBounds(390, 140, 120, 14);

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel12.setText("Allergier");
        add(jLabel12);
        jLabel12.setBounds(200, 200, 50, 14);

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setText("Fornavn");
        add(jLabel3);
        jLabel3.setBounds(200, 40, 50, 14);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel4.setText("Efternavn");
        add(jLabel4);
        jLabel4.setBounds(390, 40, 70, 14);

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel5.setText("Adresse");
        add(jLabel5);
        jLabel5.setBounds(10, 90, 60, 14);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel8.setText("Post nr.");
        add(jLabel8);
        jLabel8.setBounds(200, 90, 60, 14);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel7.setText("By");
        add(jLabel7);
        jLabel7.setBounds(390, 90, 30, 14);

        txtElevBy.setEditable(false);
        add(txtElevBy);
        txtElevBy.setBounds(390, 110, 170, 20);

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel9.setText("Mobil");
        add(jLabel9);
        jLabel9.setBounds(10, 140, 30, 14);

        btnElevTilfojAllergi.setText("Tilføj");
        btnElevTilfojAllergi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnElevTilfojAllergiActionPerformed(evt);
            }
        });
        add(btnElevTilfojAllergi);
        btnElevTilfojAllergi.setBounds(200, 250, 60, 23);

        jScrollPane8.setViewportView(listElevAllergi);

        add(jScrollPane8);
        jScrollPane8.setBounds(270, 250, 100, 60);

        btnElevSletAllergi.setText("Slet");
        btnElevSletAllergi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnElevSletAllergiActionPerformed(evt);
            }
        });
        add(btnElevSletAllergi);
        btnElevSletAllergi.setBounds(200, 280, 60, 23);

        jLabel13.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel13.setText("Medicin");
        add(jLabel13);
        jLabel13.setBounds(10, 200, 50, 14);

        btnElevTilfojMedicin.setText("Tilføj");
        btnElevTilfojMedicin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnElevTilfojMedicinActionPerformed(evt);
            }
        });
        add(btnElevTilfojMedicin);
        btnElevTilfojMedicin.setBounds(10, 250, 60, 23);

        jScrollPane2.setViewportView(listElevMedicin);

        add(jScrollPane2);
        jScrollPane2.setBounds(80, 250, 100, 60);

        btnElevSletMedicin.setText("Slet");
        btnElevSletMedicin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnElevSletMedicinActionPerformed(evt);
            }
        });
        add(btnElevSletMedicin);
        btnElevSletMedicin.setBounds(10, 280, 60, 23);

        btnInsertBillede.setText("Indsæt Billede");
        btnInsertBillede.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInsertBilledeActionPerformed(evt);
            }
        });
        add(btnInsertBillede);
        btnInsertBillede.setBounds(580, 240, 190, 23);

        btnGemElev.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnGemElev.setText("Opret Ny Elev");
        btnGemElev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGemElevActionPerformed(evt);
            }
        });
        add(btnGemElev);
        btnGemElev.setBounds(10, 620, 130, 23);

        btnSletElev.setText("Slet Elev");
        btnSletElev.setEnabled(false);
        btnSletElev.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSletElevActionPerformed(evt);
            }
        });
        add(btnSletElev);
        btnSletElev.setBounds(150, 620, 80, 23);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Noter");
        add(jLabel1);
        jLabel1.setBounds(10, 490, 50, 10);

        txtaElevNote.setColumns(20);
        txtaElevNote.setRows(5);
        jScrollPane1.setViewportView(txtaElevNote);

        add(jScrollPane1);
        jScrollPane1.setBounds(10, 510, 550, 90);

        listFiler.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane6.setViewportView(listFiler);

        add(jScrollPane6);
        jScrollPane6.setBounds(10, 340, 550, 100);

        jLabel25.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel25.setText("Vedhæftede Filer");
        add(jLabel25);
        jLabel25.setBounds(10, 320, 100, 14);

        btnVedhaeftFil.setText("Vedhæft Fil");
        btnVedhaeftFil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVedhaeftFilActionPerformed(evt);
            }
        });
        add(btnVedhaeftFil);
        btnVedhaeftFil.setBounds(395, 450, 90, 23);

        btnOpenFil.setText("Åben Fil");
        btnOpenFil.setToolTipText("Her kan du åbne den fil du har valgt");
        btnOpenFil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenFilActionPerformed(evt);
            }
        });
        add(btnOpenFil);
        btnOpenFil.setBounds(10, 450, 100, 23);

        btnFjernValgteFil.setText("Slet Fil");
        btnFjernValgteFil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFjernValgteFilActionPerformed(evt);
            }
        });
        add(btnFjernValgteFil);
        btnFjernValgteFil.setBounds(490, 450, 70, 23);

        btnPrint.setText("Print Elev Social Info");
        btnPrint.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPrintActionPerformed(evt);
            }
        });
        add(btnPrint);
        btnPrint.setBounds(580, 550, 190, 23);
        add(txtElevcpr);
        txtElevcpr.setBounds(10, 60, 170, 20);
        add(jSeparator1);
        jSeparator1.setBounds(0, 190, 570, 10);

        jSeparator2.setOrientation(javax.swing.SwingConstants.VERTICAL);
        add(jSeparator2);
        jSeparator2.setBounds(570, 0, 10, 610);
        add(jSeparator3);
        jSeparator3.setBounds(0, 610, 780, 10);

        jSeparator4.setOrientation(javax.swing.SwingConstants.VERTICAL);
        add(jSeparator4);
        jSeparator4.setBounds(780, 0, 10, 610);

        jButton1.setText("Print Elev Faglig Info");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        add(jButton1);
        jButton1.setBounds(580, 580, 190, 23);

        btnFortryd.setText("Fortryd Ændringer");
        btnFortryd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFortrydActionPerformed(evt);
            }
        });
        add(btnFortryd);
        btnFortryd.setBounds(10, 650, 130, 23);
    }// </editor-fold>//GEN-END:initComponents

    private void cbElevNavnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbElevNavnActionPerformed
        lIconBilledeElev.setIcon(null);
        elevBilledePanel.validate();
        ArrayList temparray = new ArrayList();
        allergier = new ArrayList();
        medicin = new ArrayList();
        filer = new ArrayList();
        session.beginTransaction();

        if (cbElevNavn.getSelectedIndex() > 0) {
            btnGemElev.setText("Gem ændringer");
            btnFortryd.setVisible(true);
            Elev elev = (Elev) cbElevNavn.getSelectedItem();
            txtElevcpr.setEditable(false);
            txtElevcpr.setText(elev.getCpr());
            txtElevFnavn.setText(elev.getFornavn());
            txtElevEnavn.setText(elev.getEfternavn());
            txtElevAdress.setText(elev.getAdresse());
            txtElevRekvKommune.setText(elev.getRekvkommune());
            txtElevRekvSkole.setText(elev.getRekvskole());
            txtaElevNote.setText(elev.getNoter());
            cbElevKlasseTrin.setSelectedIndex(elev.getNiveau());
            
            if (elev.getHold() != null) {
                cbElevHold.setSelectedItem(elev.getHold());
            } else {
                cbElevHold.setSelectedIndex(0);
            }
            
            if (elev.getPostnrbynavn() != null) {
                txtElevPostnr.setText(elev.getPostnrbynavn().getPostnr());
                txtElevBy.setText(getByNavn(elev.getPostnrbynavn().getPostnr()));
            } else {
                txtElevPostnr.setText("");
                txtElevBy.setText("");
            }
            
            if (elev.getIndskrevet() != null) {
                chbIndskrevet.setSelected(true);
                spElevIndskrevet.setValue(elev.getIndskrevet());
            } else {
                chbIndskrevet.setSelected(false);
                spElevIndskrevet.setValue(new Date());
            }
            
            if (elev.getUdskrevet() != null) {
                chbUdskrevet.setSelected(true);
                spElevUdskrevet.setValue(elev.getUdskrevet());
            } else {
                chbUdskrevet.setSelected(false);
                spElevUdskrevet.setValue(new Date());
            }
            
            if (getElevTlf(elev.getCpr()) != null) {
                txtElevMobilNr.setText(getElevTlf(elev.getCpr()));
            } else {
                txtElevMobilNr.setText("");
            }

            temparray.addAll(elev.getElevallergis());
            for (int i = 0; i < temparray.size(); i++) {
                Elevallergi ea = (Elevallergi) temparray.get(i);
                allergier.add(ea.getId().getAllergi());
            }
            listElevAllergi.setListData(allergier.toArray());
            temparray = new ArrayList();
            temparray.addAll(elev.getElevmedicins());
            for (int i = 0; i < temparray.size(); i++) {
                Elevmedicin em = (Elevmedicin) temparray.get(i);
                medicin.add(em.getId().getMedicin());
            }
            listElevMedicin.setListData(medicin.toArray());
            temparray = new ArrayList();
            temparray.addAll(elev.getElevfilers());
            for (int i = 0; i < temparray.size(); i++) {
                Elevfiler ef = (Elevfiler) temparray.get(i);
                File newImage = new File(ef.getId().getFilUri());
                filer.add(newImage);
            }
            listFiler.setListData(filer.toArray());
            Image billede = null;
            try {
                billede = ImageIO.read(new File(elev.getBilledeUri()));
                billede = billede.getScaledInstance(elevBilledePanel.getWidth(), elevBilledePanel.getHeight(), Image.SCALE_SMOOTH);
                ImageIcon icon = new ImageIcon(billede);
                lIconBilledeElev.setIcon(icon);
            } catch (Exception ex) {
                System.out.println("ikke et billede " + ex);
            }
            btnSletElev.setEnabled(true);
            needtoupdate = true;
        } else {
            btnGemElev.setText("Opret ny elev");
            btnFortryd.setVisible(false);
            if (needtoupdate) {
                update();
                needtoupdate = false;
            }
            txtElevcpr.setEditable(true);
            btnSletElev.setEnabled(false);
        }
    }//GEN-LAST:event_cbElevNavnActionPerformed

    private void txtElevPostnrKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtElevPostnrKeyReleased
        if (txtElevPostnr.getText().length() == 4) {
            txtElevBy.setText(getByNavn(txtElevPostnr.getText()));
        } else {
            txtElevBy.setText("");
        }
    }//GEN-LAST:event_txtElevPostnrKeyReleased

    private void btnElevTilfojAllergiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnElevTilfojAllergiActionPerformed
        if (txtElevAllergi.getText().length() > 0) {
            String allergi = txtElevAllergi.getText();
            allergier.add(allergi);
            listElevAllergi.setListData(allergier.toArray());
            txtElevAllergi.setText("");
        }
    }//GEN-LAST:event_btnElevTilfojAllergiActionPerformed

    private void btnElevSletAllergiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnElevSletAllergiActionPerformed
        if (!listElevAllergi.isSelectionEmpty()) {
            allergier.remove(listElevAllergi.getSelectedIndex());
            listElevAllergi.setListData(allergier.toArray());
        }
    }//GEN-LAST:event_btnElevSletAllergiActionPerformed

    private void btnElevTilfojMedicinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnElevTilfojMedicinActionPerformed
        if (txtElevMedicin.getText().length() > 0) {
            String allergi = txtElevMedicin.getText();
            medicin.add(allergi);
            listElevMedicin.setListData(medicin.toArray());
            txtElevMedicin.setText("");
        }
    }//GEN-LAST:event_btnElevTilfojMedicinActionPerformed

    private void btnElevSletMedicinActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnElevSletMedicinActionPerformed
        if (!listElevMedicin.isSelectionEmpty()) {
            medicin.remove(listElevMedicin.getSelectedIndex());
            listElevMedicin.setListData(medicin.toArray());
        }
    }//GEN-LAST:event_btnElevSletMedicinActionPerformed

    private void btnInsertBilledeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsertBilledeActionPerformed
        Image billede = null;
        JFileChooser fc = new JFileChooser();
        FileNameExtensionFilter filter = new FileNameExtensionFilter("Billedfiler", "png", "jpg", "jpeg");
        fc.setFileFilter(filter);
        int returnVal = fc.showDialog(null, "Indsæt billede");
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File newImage = fc.getSelectedFile();
            billedefil = newImage;
            try {
                billede = ImageIO.read(newImage);
            } catch (IOException ex) {
                System.out.println("ikke et billede");
            }
            billede = billede.getScaledInstance(elevBilledePanel.getWidth(), -1, Image.SCALE_SMOOTH);
            ImageIcon icon = new ImageIcon(billede);
            lIconBilledeElev.setIcon(icon);
        }
    }//GEN-LAST:event_btnInsertBilledeActionPerformed

    private void btnGemElevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGemElevActionPerformed
        try {
            needtoupdate = false;
            String billedUri = "";
            Elev elev = null;

            if (cbElevNavn.getSelectedIndex() == 0) {
                if (txtElevcpr.getText().length() == 10 && txtElevFnavn.getText().length() > 0 && txtElevEnavn.getText().length() > 0) {
                    session.beginTransaction();
                    elev = new Elev(txtElevcpr.getText());
                    session.save(elev);
                    session.getTransaction().commit();
                    session.flush();
                } else {
                    JOptionPane.showMessageDialog(null, "Eleven skal have fornavn, efternavn og CPR nummeret skal være indtastet rigtgt eks. 1234567890", "Info", 1);
                }
            } else {
                session.beginTransaction();
                elev = (Elev) cbElevNavn.getSelectedItem();
                billedUri = elev.getBilledeUri();
                elev.getElevtlfs().removeAll(elev.getElevtlfs());
                elev.getElevallergis().removeAll(elev.getElevallergis());
                elev.getElevmedicins().removeAll(elev.getElevmedicins());
                elev.getElevfilers().removeAll(elev.getElevfilers());
                session.update(elev);
                session.getTransaction().commit();
                session.flush();
            }
            
            if (elev != null) {
                session.beginTransaction();
                elev.setFornavn(txtElevFnavn.getText());
                elev.setEfternavn(txtElevEnavn.getText());
                elev.setNiveau(cbElevKlasseTrin.getSelectedIndex());
                elev.setAdresse(txtElevAdress.getText());
                elev.setRekvkommune(txtElevRekvKommune.getText());
                elev.setRekvskole(txtElevRekvSkole.getText());
                elev.setNoter(txtaElevNote.getText());
                String hql = "from Postnrbynavn where postnr='" + txtElevPostnr.getText() + "'";
                Query q = session.createQuery(hql);
                Postnrbynavn pbn = (Postnrbynavn) q.uniqueResult();
                if (pbn != null) {
                    elev.setPostnrbynavn(pbn);
                    pbn.getElevs().add(elev);
                }
                if (txtElevMobilNr.getText().length() == 8) {
                    ElevtlfId tlfid = new ElevtlfId(txtElevcpr.getText(), txtElevMobilNr.getText());
                    Elevtlf mobil = new Elevtlf(tlfid, elev);
                    elev.getElevtlfs().add(mobil);
                }

                for (int i = 0; i < allergier.size(); i++) {
                    ElevallergiId eaid = new ElevallergiId(txtElevcpr.getText(), (String) allergier.get(i));
                    Elevallergi ea = new Elevallergi(eaid, elev);
                    elev.getElevallergis().add(ea);
                }

                for (int i = 0; i < medicin.size(); i++) {
                    ElevmedicinId emid = new ElevmedicinId(txtElevcpr.getText(), (String) medicin.get(i));
                    Elevmedicin em = new Elevmedicin(emid, elev);
                    elev.getElevmedicins().add(em);
                }

                if (cbElevHold.getSelectedIndex() > 0) {
                    elev.setHold((Hold) cbElevHold.getSelectedItem());
                } else {
                    elev.setHold(null);
                }

                if (chbIndskrevet.isSelected()) {
                    elev.setIndskrevet((Date) spElevIndskrevet.getModel().getValue());
                } else {
                    elev.setIndskrevet(null);
                }
                if (chbUdskrevet.isSelected()) {
                    elev.setUdskrevet((Date) spElevUdskrevet.getModel().getValue());
                } else {
                    elev.setUdskrevet(null);
                }

                String pre = "AttachedFiles/";
                pre += elev.getFornavn() + elev.getEfternavn();
                File f = new File(pre);
                f.mkdirs();
                String path = "";
                String fName = "";
                for (int i = 0; i < filer.size(); i++) {
                    path = ((File) filer.get(i)).getPath();
                    fName = pre + "/" + ((File) filer.get(i)).getName();
                    if (!path.equals(fName)) {
                        try {
                            FileUtils.copy(path, fName);
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(null, ex.getLocalizedMessage(), "File Error!", 0);
                        }
                        ElevfilerId efid = new ElevfilerId(elev.getCpr(), fName);
                        Elevfiler ef = new Elevfiler(efid, elev);
                        elev.getElevfilers().add(ef);
                    }
                }

                if (billedefil != null) {
                    path = billedefil.getPath();
                    fName = pre + "/ElevBillede";
                    if (!path.equals(fName)) {
                        try {
                            FileUtils.copy(path, fName);
                        } catch (IOException ex) {
                            JOptionPane.showMessageDialog(null, ex.getLocalizedMessage(), "File Error!", 0);
                        }
                    }
                    elev.setBilledeUri(fName);
                    billedefil = null;
                } else {
                    elev.setBilledeUri(billedUri);
                }
                
                if (filerDerSlettes.size() > 0) {
                    for (int i = 0; i < filerDerSlettes.size(); i++) {
                        File fil = (File) filerDerSlettes.get(i);
                        fil.delete();
                    }
                }
                session.saveOrUpdate(elev);
                session.getTransaction().commit();
                session.flush();
                update();
                allergier = new ArrayList();
                medicin = new ArrayList();
                filer = new ArrayList();
                filerDerSlettes = new ArrayList();
                JOptionPane.showMessageDialog(null, "Eleven er gemt.", "Info", 1);
            }
        } catch (NonUniqueObjectException e) {
            JOptionPane.showMessageDialog(null, "En elev med CPR nummeret " + txtElevcpr.getText() + " findes allerede i databasen", "Info", 1);
        }
    }//GEN-LAST:event_btnGemElevActionPerformed

    private void btnSletElevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSletElevActionPerformed
        needtoupdate = false;
        int result = JOptionPane.showConfirmDialog(null, "Er du sikker på du vil slette den valgte elev og alle tilhørende data", "Advarsel", 2);
        if (result == JOptionPane.OK_OPTION) {
            
            Elev e = (Elev) cbElevNavn.getSelectedItem();
            ArrayList temp = new ArrayList();
            temp.addAll(e.getKontaktpersons());
            for (int i = 0; i < temp.size(); i++) {
                Kontaktperson kp = (Kontaktperson) temp.get(i);
                if (kp.getElevs().size() == 1){
                    session.beginTransaction();
                    e.getKontaktpersons().remove(kp);
                    session.delete(kp);
                    session.update(e);
                    session.getTransaction().commit();
                }else{
                    session.beginTransaction();
                    kp.getElevs().remove(e);
                    session.update(kp);
                    session.getTransaction().commit();
                }         
            }
            if (e.getElevfilers().size() > 0) {
                filerDerSlettes = new ArrayList();
                filerDerSlettes.addAll(e.getElevfilers());
                for (int i = 0; i < filerDerSlettes.size(); i++) {
                    Elevfiler ef = (Elevfiler) filerDerSlettes.get(i);
                    File newImage = new File(ef.getId().getFilUri());
                    newImage.delete();
                }
            }
            session.beginTransaction();
            session.delete(e);
            session.getTransaction().commit();
            session.flush();
            update();
        }
    }//GEN-LAST:event_btnSletElevActionPerformed

    private void btnVedhaeftFilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVedhaeftFilActionPerformed
        JFileChooser fc = new JFileChooser();
        int returnVal = fc.showDialog(null, "Vedhæft fil");
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File newFile = fc.getSelectedFile();
            filer.add(newFile);
            listFiler.setListData(filer.toArray());
        }
    }//GEN-LAST:event_btnVedhaeftFilActionPerformed

    private void btnOpenFilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenFilActionPerformed
        if (!listFiler.isSelectionEmpty()) {
            File temp = (File) filer.get(listFiler.getSelectedIndex());
            Desktop dtop = Desktop.getDesktop();
            try {
                dtop.open(temp);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, ex.getLocalizedMessage(), "File Error!", 0);
            }
        }
    }//GEN-LAST:event_btnOpenFilActionPerformed

    private void btnFjernValgteFilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFjernValgteFilActionPerformed
        if (!listFiler.isSelectionEmpty()) {
            File f = (File) filer.get(listFiler.getSelectedIndex());
            filerDerSlettes.add(f);
            filer.remove(listFiler.getSelectedIndex());
            listFiler.setListData(filer.toArray());
        }
    }//GEN-LAST:event_btnFjernValgteFilActionPerformed

    private void btnPrintActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrintActionPerformed
        if (cbElevNavn.getSelectedIndex() > 0) {
            Elev e = (Elev) cbElevNavn.getSelectedItem();
            PrintUtils.printElevInfo(e);
        }
    }//GEN-LAST:event_btnPrintActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if (cbElevNavn.getSelectedIndex() > 0) {
            Elev e = (Elev) cbElevNavn.getSelectedItem();
            PrintUtils.printElevHandleplan(e);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnFortrydActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFortrydActionPerformed
        // TODO add your handling code here:
        cbElevNavnActionPerformed(evt);
    }//GEN-LAST:event_btnFortrydActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnElevSletAllergi;
    private javax.swing.JButton btnElevSletMedicin;
    private javax.swing.JButton btnElevTilfojAllergi;
    private javax.swing.JButton btnElevTilfojMedicin;
    private javax.swing.JButton btnFjernValgteFil;
    private javax.swing.JButton btnFortryd;
    private javax.swing.JButton btnGemElev;
    private javax.swing.JButton btnInsertBillede;
    private javax.swing.JButton btnOpenFil;
    private javax.swing.JButton btnPrint;
    private javax.swing.JButton btnSletElev;
    private javax.swing.JButton btnVedhaeftFil;
    private javax.swing.JComboBox cbElevHold;
    private javax.swing.JComboBox cbElevKlasseTrin;
    private javax.swing.JComboBox cbElevNavn;
    private javax.swing.JCheckBox chbIndskrevet;
    private javax.swing.JCheckBox chbUdskrevet;
    private javax.swing.JPanel elevBilledePanel;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JScrollPane jScrollPane8;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JLabel lIconBilledeElev;
    private javax.swing.JList listElevAllergi;
    private javax.swing.JList listElevMedicin;
    private javax.swing.JList listFiler;
    private javax.swing.JSpinner spElevIndskrevet;
    private javax.swing.JSpinner spElevUdskrevet;
    private javax.swing.JTextField txtElevAdress;
    private javax.swing.JTextField txtElevAllergi;
    private javax.swing.JTextField txtElevBy;
    private javax.swing.JTextField txtElevEnavn;
    private javax.swing.JTextField txtElevFnavn;
    private javax.swing.JTextField txtElevMedicin;
    private javax.swing.JTextField txtElevMobilNr;
    private javax.swing.JTextField txtElevPostnr;
    private javax.swing.JTextField txtElevRekvKommune;
    private javax.swing.JTextField txtElevRekvSkole;
    private javax.swing.JTextField txtElevcpr;
    private javax.swing.JTextArea txtaElevNote;
    // End of variables declaration//GEN-END:variables
}
